package com.excesys;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

// 动态代理处理器
class DynamicInvocationHandler implements InvocationHandler {
    private Object target;

    public DynamicInvocationHandler(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("Dynamic proxy is doing some preprocessing...");

        Object result = method.invoke(target, args);

        System.out.println("Dynamic proxy is doing some postprocessing...");

        return result;
    }
}

// 目标接口
interface Service {
    void doSomething();
}

// 目标类（被代理类）
class RealService implements Service {
    @Override
    public void doSomething() {
        System.out.println("Real service doing something...");
    }
}

// 使用示例
public class Main {
    public static void main(String[] args) {
        Service realService = new RealService();

        // 创建动态代理对象
        Service dynamicProxy = (Service) Proxy.newProxyInstance(Service.class.getClassLoader(), new Class<?>[]{Service.class}, new DynamicInvocationHandler(realService));

        dynamicProxy.doSomething(); // 输出动态代理预处理 -> 真实服务执行 -> 动态代理后处理
    }
}
